package study.仪器解析.串口化通信.生化仪.监听COM1;


import com.fazecast.jSerialComm.SerialPort;

/**
 * @Author 刘伟涛
 * @Date 2024/8/7 13:49
 **/
public class 双向通信Send {
    public static void main(String[] args) throws InterruptedException {
        // 指定串口名称，如 COM1, COM2, /dev/ttyUSB0
        String portName = "COM2";
//        SerialPort serialPort = new SerialPort(portName);
        SerialPort serialPort = com.fazecast.jSerialComm.SerialPort.getCommPort(portName); // 指定串口名称
        serialPort.setBaudRate(9600);
        serialPort.setNumDataBits(8);
        serialPort.setNumStopBits(com.fazecast.jSerialComm.SerialPort.ONE_STOP_BIT);
        serialPort.setParity(com.fazecast.jSerialComm.SerialPort.NO_PARITY);

        if (serialPort.openPort()) {
            System.out.println("串口打开成功！");
        } else {
            System.out.println("串口打开失败！");
            return;
        }
            // 发送数据 16进制查询码
            // 检测结果样例
            String dataToSend = "\u00021H|\\^&|||1|||||2||1|20240823162037\r\u000312\r\n" +
                    "\u00022P|4|||||||男||||||^Y\r\u000312\r\n" +
                    "\u00023O|1|KN2412477^4^1^4|||R|20240826154624|||||||||1||||||||||O\r\u000312\r\n" +
                    "\u00024R|1|^^^ALT|5.58|U/L|0^50\\^|||F||||20240826154624\r\u000312\r\n" +
                    "\u00025L|1|N\r\u000312\r\n" +
                    "\u0004";
            // 质控数据样例
            String dataToSend2 = "\u00021H|\\^&|||1|||||2||1|20240827164512\r\u000312\r\n" +
                    "\u00022P|1||||QC|||||||||^\r\u000312\r\n" +
                    "\u00023O|1|^0^1^C1^|伯乐生化多项质控品^45981(20240801)^|||20240826153351|||||||||1||||||||||O\r\u000312\r\n" +
                    "\u00024R|1|^^^ALT|31.02|U/L|31.3^0.81||-1SD|||||20240826153351\r\u000312\r\n" +
                    "\u00025L|1|N\r\u000312\r\n" +
                    "\u0004";
        byte[] data = dataToSend.getBytes();
            serialPort.writeBytes(data,data.length);
            // 串口bidirectionalCommunication
            // 读取响应
            Thread.sleep(100);
        byte[] newData = new byte[serialPort.bytesAvailable()];
        int numRead = serialPort.readBytes(newData, newData.length);
        System.out.println("Received data: " + new String(newData));

            // 关闭串口
            serialPort.closePort();
    }
}
